import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import $store from '../store';
import { $pushRoute, useGlobalMessage } from './global';

const config: AxiosRequestConfig = {
  // baseURL: process.env.baseURL,
  // baseURL: 'http://134.175.60.227/api',
  baseURL: 'http://localhost/api',
  timeout: 3000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  withCredentials: true,
};

const request: AxiosInstance = axios.create(config);


// http response 拦截器
axios.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    //拦截响应，做统一处理
    if (response?.data?.code) {
      switch (response?.data?.code) {
        case 401:
          useGlobalMessage().error('登录过期, 请重新登录！');
          $store.dispatch('clearUserInfo');
          $pushRoute('/login');
          break;
      }
      if (response.data.code > 200) {
        !(response.config as any)?.customError && useGlobalMessage().error(response.data.message || '未知错误');
      }
    }
    (response as any).raw = response;
    return (response.config as any).useRaw ? response : response.data || {};
  },
  //接口错误状态处理，也就是说无响应时的处理
  error => {
    useGlobalMessage().error('网络错误，请联系管理员解决！');
    console.log(error);
    return Promise.reject(error?.response?.status) // 返回接口返回的错误信息
  });

axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 可在这里做一些数据的校验。
    // session的校验等。
    return config
  },
  (error: AxiosError) => {
    return error
  }
)

//封装下post
export const $post = request.post = function (url, params, extraConfig: any = {}) {
  return new Promise<any>((resolve, reject) => {
    axios
      .post(
        config.baseURL + url,
        params, {
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
        },
        withCredentials: true,
        ...extraConfig,
      }).then(response => {
        if (((response as any)?.raw?.data || response).code == 200) {
          //根据实际情况进行更改
          resolve(response)
        } else {
          reject(response)
        }
      })
  })
}

export const $get = request.get = function (url: string, params: any, extraConfig: any = {}) {
  return new Promise<any>((resolve, reject) => {
    axios
      .get(
        config.baseURL + url, {
        params: params,
        withCredentials: true,
        ...extraConfig,
      })
      .then((response) => {
        resolve(response);
      })
      .catch(err => {
        reject(err);
      });
  });
}

export default request;
